package com.yl.users.common.util

import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.yl.users.common.annotations.FilterField
import com.yl.users.common.annotations.PermsCode

/**
 * 返回字段权限处理工具类
 */
class FieldPermUtil {

    fun filterField(code: Set<String>, o: Any?) {
        if (o != null) {
            if (o is Page<*>) {
                val list = o.records
                for (obj in list) {
                    filterObjField(code, obj)
                }
            } else if (o is List<*>) {
                for (obj in o) {
                    filterObjField(code, obj!!)
                }
            } else {
                filterObjField(code, o)
            }
        }
    }

    private fun filterObjField(code: Set<String>, o: Any) {
        val fs = o.javaClass.declaredFields
        try {
            for (f in fs) {
                val showField: PermsCode? = f.getAnnotation(PermsCode::class.java)
                if (showField != null) {
                    val value = showField.value
                    if (!code.contains(value)) {
                        f[o] = null
                        continue
                    }
                }
                val filterField: FilterField? = f.getAnnotation(FilterField::class.java)
                if (filterField != null) {
                    filterField(code, f)
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


}